package cn.wolfcode.shop.cloud.reslove;

import cn.wolfcode.shop.cloud.RedisService;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import cn.wolfcode.shop.cloud.util.MemberKeyPrefix;
import cn.wolfcode.shop.cloud.util.UserAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;

public class UserArgumentsResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private RedisService redisService;


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return  parameter.getParameterAnnotation(UserAnnotation.class) != null &&  parameter.getParameterType() == User.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = CookieUtil.getCookie(request,"token");
        if(token == null){
            return null;
        }
        return  redisService.get(MemberKeyPrefix.USER_TOKEN,token,User.class);
    }
}
